# -- coding:UTF-8 --

import logging
import random
import time
import json
import pyperclip
import requests
import pyautogui
import os,signal
import cv2
import sys
import urllib3
# from clicknium import clicknium as cc, locator
import subprocess
from pathlib import Path
import glob
# import chardet
# import mysql.connector
import shutil
from configparser import ConfigParser
from datetime import datetime
import base64

# 创建解析器对象
config = ConfigParser()
 
# 读取配置文件
config.read('config.ini')

# db_user = config.get('database', 'user')
# db_password = config.get('database', 'password')
# db_host = config.get('database', 'host')
# db_name = config.get('database', 'db_name')
# db_port = config.getint('database', 'port') 

telegram_path = config.get('telegram', 'path') 

path = os.getcwd()

global_headers = {
    'Host': 'gateway.blum.codes',
    'sec-ch-ua': '"Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99", "Microsoft Edge WebView2";v="124"',
    'accept': 'application/json, text/plain, */*',
    'content-type': 'application/json',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://telegram.blum.codes',
    'sec-fetch-site': 'same-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'priority': 'u=1, i',
}

class BlumTokenWorker:
    logger = logging.getLogger(__name__)

    accounts = 9
    flag = 1

    sleep_gap = 30

    # current_token = ""

    # 刷新TOKEN
    def refreshToken(self):

        # 通过接口抓取数据库里的所有记录，遍历刷新
        get_tokens_response = requests.get('http://43.134.224.49/api/blum/token',  verify=False, timeout=8)
        get_tokens_response_json = json.loads(get_tokens_response.content)

        json_data = json.loads(json.dumps(get_tokens_response_json))

        # print(json_array['data'])

        responese_array = json_data['data']

        for item in responese_array:
            # {'id': 10730, 
            # 'game_id': '3fd44907-d99d-420a-b93f-9d15ad34fd8b', 
            # 'proxy': None, 'success': 0, 'fail': 0, 
            # 'access_token': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJoYXNfZ3Vlc3QiOmZhbHNlLCJ0eXBlIjoiQUNDRVNTIiwiaXNzIjoiYmx1bSIsInN1YiI6IjNmZDQ0OTA3LWQ5OWQtNDIwYS1iOTNmLTlkMTVhZDM0ZmQ4YiIsImV4cCI6MTcxOTY3NzIzMCwiaWF0IjoxNzE5NjczNjMwfQ.yd1A548t_GtX7vwSN_fTxCarCNHxkWjOcNQK15sPbec', 
            # 'access_token_expire': 1719677230, 
            # 'refresh_token': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJoYXNfZ3Vlc3QiOmZhbHNlLCJ0eXBlIjoiUkVGUkVTSCIsImlzcyI6ImJsdW0iLCJzdWIiOiIzZmQ0NDkwNy1kOTlkLTQyMGEtYjkzZi05ZDE1YWQzNGZkOGIiLCJleHAiOjE3MTk3NjAwMzAsImlhdCI6MTcxOTY3MzYzMH0.G45HN8EDIMsg4csvPr8U9G0YMM6sIAx1IBeWjeTt87w', 
            # 'refresh_token_expire': 1719760030, 'score': None}
            # print(item['id'])

            random_num = random.randint(10, 40)
            print(f'休眠 {random_num} 秒再继续刷新')
            time.sleep(random_num)
            # 将时间戳转换为datetime对象
            # 首先获取当前时间戳（秒级）
            timestamp_seconds_current = time.time()
            token_expire = datetime.fromtimestamp(item['access_token_expire'])
            datetime_current = datetime.fromtimestamp(timestamp_seconds_current)

            print("datetime_current:", datetime_current)
            print("token_expire    :", token_expire)
            
            # 计算时间差
            difference = token_expire - datetime_current
            
            # 输出时间差
            print(f"id 为 {item['id']} 的token 还剩 {difference.total_seconds()} seconds 过期.")

            refresh_token = item['refresh_token']

            # print(access_token)
            if refresh_token.strip() != "":
                json_data = {
                    'refresh': refresh_token.replace("Bearer ",""),
                }
                
                try:
                    response = requests.post('https://gateway.blum.codes/v1/auth/refresh', headers=global_headers, json=json_data, verify=False, timeout=8)
                    refrest_response_json = json.loads(response.content)
                    # print(response.content)
                    if "access" in refrest_response_json:
                        # 刷新token成功

                        access_token = refrest_response_json['access']
                        refreshedAccessToken = "Bearer " + refrest_response_json['access']
                        
                        refresh_token = refrest_response_json['refresh']
                        refreshedRefreshToken = "Bearer " + refrest_response_json['refresh']
                        
                        # 把新的token写入数据库

                        # 解析刚获取到的access token, 用.号进行split
                        access_token_splited = access_token.split(".")
                        access_token_splited_token_index1 = access_token_splited[1]
                        
                        # 解析刚获取到的refresh token, 用.号进行split
                        refresh_token_splited = refresh_token.split(".")
                        refresh_token_splited_token_index1 = refresh_token_splited[1]

                        # base64解析 access token
                        access_token_splited_token_index1 += "=" * ((4 - len(access_token_splited_token_index1) % 4) % 4)
                        access_token_decoded_string = base64.b64decode(access_token_splited_token_index1)
                        access_token_decoded_string_utf8 = access_token_decoded_string.decode("utf-8")

                        access_token_parsed_token_json = json.loads(access_token_decoded_string_utf8)

                        access_token_token_expire_timestamp = access_token_parsed_token_json['exp']
                        game_id = access_token_parsed_token_json['sub']
                        
                        # base64解析 refresh token
                        refresh_token_splited_token_index1 += "=" * ((4 - len(refresh_token_splited_token_index1) % 4) % 4)
                        refresh_token_decoded_string = base64.b64decode(refresh_token_splited_token_index1)
                        refresh_token_decoded_string_utf8 = refresh_token_decoded_string.decode("utf-8")

                        refresh_token_parsed_token_json = json.loads(refresh_token_decoded_string_utf8)

                        refresh_token_token_expire_timestamp = refresh_token_parsed_token_json['exp']
                        # game_id = parsed_token_json['sub']
                    
                        payload = {
                            "game_id":""+game_id,
                            "access_token":refreshedAccessToken,
                            "access_token_expire":access_token_token_expire_timestamp,
                            "refresh_token":refreshedRefreshToken,
                            "refresh_token_expire":refresh_token_token_expire_timestamp
                        }
                        
                        headers_a = {
                            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",
                            'Accept': "application/json, text/plain, */*",
                            'Accept-Encoding': "gzip, deflate, br, zstd",
                            'Content-Type': "application/json",
                            'sec-ch-ua': "\"Chromium\";v=\"124\", \"Microsoft Edge\";v=\"124\", \"Not-A.Brand\";v=\"99\", \"Microsoft Edge WebView2\";v=\"124\"",
                            'sec-ch-ua-mobile': "?0",
                            'sec-ch-ua-platform': "\"Windows\"",
                            'sec-fetch-site': "same-site",
                            'sec-fetch-mode': "cors",
                            'sec-fetch-dest': "empty",
                            'accept-language': "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
                            'priority': "u=1, i" 
                        }
                        
                        update_result_response = requests.post('http://43.134.224.49/api/blum/token', headers=headers_a, json=payload, verify=False, timeout=8)
                        # print(payload)
                        # print(update_result_response.content)
                    
                except Exception as e1:
                    print(f"Request new token ERROR: {e1.with_traceback}")
                # 关闭游标和连接
    # 解析token
    def parse_token(self, token):
        splited = token.split(".")
        return splited[1]
    
    def base64_parse_token(self, token):
        token += "=" * ((4 - len(token) % 4) % 4)
        decoded_string = base64.b64decode(token)
        return decoded_string.decode("utf-8")
   
    def _loop(self):
        print("Start......")
        # self.request_telegram_portable()
        self.refreshToken()
        # if self.current_token.strip() != "":
        #     self.fetchTasks()
        #     self.refreshToken(self.flag)
        #     self.getBalance()       
        self.flag = self.flag + 1
        if self.flag > self.accounts:
            self.flag = 1

if __name__ == '__main__':
    bw = BlumTokenWorker()
    print('begin work......')
    while 1 == 1:
        bw._loop()
        # bw._loop()
    print('done.....')
